#include "selectcalldatadialog.h"

SelectCallDataDialog::SelectCallDataDialog(QWidget *parent, Qt::WFlags f)
    : QWidget(parent, f)
{
	setupUi(this);

	dir = QDir::home(); // QDir::current()
	dir.cd("Documents_PC");
	dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::Readable);
	dir.setSorting(QDir::Name | QDir::IgnoreCase);	
}

SelectCallDataDialog::~SelectCallDataDialog()
{
}

void SelectCallDataDialog::showList(QString defaultFile, QString extension, QString 	
		currentFile, QString randomFile) 
{	
	this->defaultItem = defaultFile + " (default)";
	QFileInfoList fileInfoList = dir.entryInfoList();
	for (int i=0; i < fileInfoList.size(); i++) {
		QFileInfo fileInfo = fileInfoList.at(i);
		if (fileInfo.fileName().endsWith(extension) && 
				fileInfo.fileName().compare(defaultFile + extension) != 0) {	
			int length = fileInfo.fileName().length() - 4;
			fileListWidget->addItem(fileInfo.fileName().left(length));
		}
	}
	
	if (!defaultFile.isEmpty()) {
		insertItem(defaultItem);
	}	
	if (!randomFile.isEmpty()) {
		insertItem(randomFile);
	}
	if (currentFile.compare(defaultFile)==0) {
		currentFile = defaultItem;
	}
	if (fileListWidget->findItems(currentFile, Qt::MatchExactly).size() != 0) {
		fileListWidget->setCurrentItem(
			fileListWidget->findItems(currentFile, Qt::MatchExactly).at(0));
	} else {
		fileListWidget->setCurrentRow(0);
	}
}

void SelectCallDataDialog::insertItem(QString item)
{
	for(int i=0; i<fileListWidget->count(); i++) {
		QString listItem = fileListWidget->item(i)->text();
		//qDebug() << listItem << "at line" <<i;
		int diff = listItem.compare(item, Qt::CaseInsensitive);
		if (diff > 0) {
			fileListWidget->insertItem(i, item);
			return;
		}
	}
	fileListWidget->insertItem(fileListWidget->count(), item);
}

void SelectCallDataDialog::on_selectPushButton_clicked()
{
	//qDebug() << "select push button";
	QListWidgetItem *selectedItem = fileListWidget->currentItem();
	QString filename = selectedItem->text();
	if (filename.endsWith(" (default)")) {
			int length = filename.length() - 10;
			filename = filename.left(length);
	}
	emit fileSelectedSignal(filename);
	close();
}

void SelectCallDataDialog::on_defaultPushButton_clicked()
{	
	if (fileListWidget->findItems(defaultItem, Qt::MatchExactly).size() != 0) {
		fileListWidget->setCurrentItem(
			fileListWidget->findItems(defaultItem, Qt::MatchExactly).at(0));
	}
}

void SelectCallDataDialog::on_cancelPushButton_clicked()
{
	this->close();
}

void SelectCallDataDialog::closeListener()
{
	close();
}

